//
//  SquareViewController.m
//  Findif
//
//  Created by Mac on 2019/1/23.
//  Copyright © 2019年 Cicel Chen. All rights reserved.
//

#import "SquareViewController.h"
#import "PushNewsViewController.h"
#import "SquareTableViewCell.h"
#import "SquareModel.h"
#import "SquareDetailViewController.h"
#import "MenuTableViewCell.h"
#import "GrayFooterView.h"
#import "MapViewController.h"
#import "GroupInfoViewController.h"
#import "GroupContractsViewController.h"
#import "ChatRoomViewController.h"
#import <JMessage/JMessage.h>
#import "PersonalViewController.h"

@interface SquareViewController ()<UITableViewDelegate,UITableViewDataSource,SquareTableViewCellDelegate>

@property (nonatomic, weak)UITableView * tableView;
@property (nonatomic, strong)NSArray <SquareModel *> * listArray;
@property (nonatomic, weak)UIView * backView;
@property (nonatomic, weak)UITableView * menuView;
@property (nonatomic, strong)NSArray * titleArray;
@property (nonatomic, strong)SquareModel * model;

@end

@implementation SquareViewController

- (void)viewWillAppear:(BOOL)animated{
    
    [self loadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = ColorWithRGB(0xF4F5F6);
//    self.titleArray = @[@"关注",@"私聊",@"邀请",@"屏蔽",@"举报"];
    
    [self setupUI];
}


- (void)loadData{
    
    [[ZRNetworkTool sharedTool] getUserDynamicWithBlock:^(BOOL success, id responseData) {

//        NSLog(@"res===%@",responseData);
        if (success) {
            self.listArray = [NSArray yy_modelArrayWithClass:[SquareModel class] json:responseData[@"data"]];
        }
    }];
    
    [self.tableView.mj_header endRefreshing];
}


- (void)setListArray:(NSArray<SquareModel *> *)listArray{
    
    _listArray = listArray;
    
    [self.tableView reloadData];
}

- (void)setTitleArray:(NSArray *)titleArray{
    
    _titleArray = titleArray;
    
    [self.menuView reloadData];
}


- (void)setupUI{
    
    UIButton * addButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20 * SCREENH6, 20 * SCREENH6)];
    
    [addButton setImage:[UIImage imageNamed:@"add"] forState:UIControlStateNormal];
    
    [addButton addTarget:self action:@selector(clickAddButton) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * rightButton = [[UIBarButtonItem alloc] initWithCustomView:addButton];
    
    self.navigationItem.rightBarButtonItem = rightButton;
    
    
    UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH - kTabBarHeight)];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = ColorWithRGB(0xF4F5F6);
//    tableView.rowHeight = 124 * SCREENH6;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.showsVerticalScrollIndicator = NO;
    
    self.tableView = tableView;
    
    [self.tableView registerClass:[SquareTableViewCell class] forCellReuseIdentifier:@"SquareReuseIdentifier"];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self loadData];
    }];
    
    [self.view addSubview:self.tableView];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    if (tableView == self.tableView) {
    
        return 1;
    }else{

        return 2;
    }

}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (tableView == self.tableView) {
        
        return self.listArray.count;
    }else{
        
        if (section == 0) {
        
            return self.titleArray.count;
        }else{

            return 1;
        }
    
    }
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == self.tableView) {
        
//        SquareTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SquareReuseIdentifier" forIndexPath:indexPath];
        
//        // 判断为空进行初始化  --（当拉动页面显示超过主页面内容的时候就会重用之前的cell，而不会再次初始化）
//        if (cell == nil) {
//            cell = [[SquareTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"SquareReuseIdentifier"];
//        }else{
//
//            //删除cell的所有子视图
//            while ([cell.contentView.subviews lastObject] != nil)
//            {
//                [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];//强制装换为UIView类型 ，移除所有子视图
//            }
//
//        }
        SquareTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; //根据indexPath准确地取出一行，而不是从cell重用队列中取出
        if (cell == nil) {
            
            cell = [[SquareTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"SquareReuseIdentifier"];
        }
        
        cell.delegate = self;
        cell.model = self.listArray[indexPath.row];
        
        return cell;
    }else{
        
        MenuTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MenuTableViewCell" forIndexPath:indexPath];
        
        if (indexPath.section == 0) {
        
            cell.showLabel.text = self.titleArray[indexPath.row];
        }else{

            cell.showLabel.text = @"取消";
        }
    
        
        return cell;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == self.tableView) {
        
        SquareDetailViewController * datailVC = [SquareDetailViewController new];
        
        SquareModel * model = self.listArray[indexPath.row];
        
        datailVC.model = model;
        
        [self.navigationController pushViewController:datailVC animated:YES];
    }else{
        
        if (indexPath.section == 0) {
            
            [self removeMenuView];
            
            if (indexPath.row == 0) {
                //关注
                NSString * user_id = [NSString stringWithFormat:@"%@",self.model.user_id];
                MenuTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
                if ([cell.showLabel.text isEqualToString:@"关注"]) {
                    
                    [[ZRNetworkTool sharedTool] attentionUseroWithUser_id:user_id ResultWithBlock:^(BOOL success, id responseData) {
                        
                        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                       message:responseData[@"message"]
                                                                                preferredStyle:UIAlertControllerStyleAlert];
                        
                        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                              handler:^(UIAlertAction * action) {
                                                                                  
                                                                              }];
                        
                        [alert addAction:defaultAction];
                        [self presentViewController:alert animated:YES completion:nil];
                    }];
                }else{
                    
                    [[ZRNetworkTool sharedTool] cancelAttentionUserUser_id:user_id ResultWithBlock:^(BOOL success, id responseData) {
                        
                        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                       message:responseData[@"message"]
                                                                                preferredStyle:UIAlertControllerStyleAlert];
                        
                        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                              handler:^(UIAlertAction * action) {
                                                                                  
                                                                              }];
                        
                        [alert addAction:defaultAction];
                        [self presentViewController:alert animated:YES completion:nil];
                    }];
                }
                
                
            }else if (indexPath.row == 1){
                //私聊
                NSString * user_id = DEF_GET_OBJECT(@"id");
                NSString * user_Str = [NSString stringWithFormat:@"%@",self.model.user_id];
                if ([user_id isEqualToString:user_Str]) {
                    
                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                   message:@"亲，不能与自己私聊"
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                          handler:^(UIAlertAction * action) {
                                                                              
                                                                              
                                                                          }];
                    
                    [alert addAction:defaultAction];
                    [self presentViewController:alert animated:YES completion:nil];
                }else{
                   
                    NSString * phone = [NSString stringWithFormat:@"%@",self.model.phone];
                    [JMSGConversation createSingleConversationWithUsername:phone completionHandler:^(id resultObject, NSError *error) {
                        
                        if (error == nil) {
                            HiddenBar;
                            ChatRoomViewController * roomVC = [ChatRoomViewController new];
                            
                            roomVC.conversation = resultObject;
                            
                            [self.navigationController pushViewController:roomVC animated:YES];
                            
                            ShowBar;
                        } else {
                            
                        }
                    }];
                }
                
            }else if (indexPath.row == 2){
                //邀请
                GroupContractsViewController * groupVC = [GroupContractsViewController new];
                
                [self.navigationController pushViewController:groupVC animated:YES];
                
                [groupVC returnGroupName:^(NSDictionary * _Nonnull localInfo) {
          
                    if (localInfo[@"ID"]) {
                        
                        NSString * groupID = localInfo[@"ID"];
                        NSString * user_id = [NSString stringWithFormat:@"%@",self.model.user_id];
                        
                        NSDictionary * dict = @{@"inform_user_id":user_id,@"group_id":groupID};
                        
                        [[ZRNetworkTool sharedTool] invitationJoinGroupWithDict:dict WithBlock:^(BOOL success, id responseData) {
                            
                            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                           message:responseData[@"message"]
                                                                                    preferredStyle:UIAlertControllerStyleAlert];
                            
                            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                                  handler:^(UIAlertAction * action) {
                                                                                      
                                                                                  }];
                            
                            [alert addAction:defaultAction];
                            [self presentViewController:alert animated:YES completion:nil];
                        }];

                    }
                }];
                
            }else if (indexPath.row == 3){
                //屏蔽
                NSString * user_id = [NSString stringWithFormat:@"%@",self.model.user_id];
                [[ZRNetworkTool sharedTool] shieldUserDynamicWithShield_user_id:user_id WithBlock:^(BOOL success, id responseData) {
                    
                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                   message:responseData[@"message"]
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                          handler:^(UIAlertAction * action) {
                                                                             
                                                                              [self loadData];
                                                                          }];
                    
                    [alert addAction:defaultAction];
                    [self presentViewController:alert animated:YES completion:nil];
                }];
                
            }else if (indexPath.row == 4){
                //举报
                NSString * ID = [NSString stringWithFormat:@"%@",self.model.id];
                NSDictionary * dict = @{@"dynamic_id":ID,@"report_cate_id":@"3"};
                
                [[ZRNetworkTool sharedTool] reportUserDynamicWithDict:dict WithBlock:^(BOOL success, id responseData) {
                    
                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                   message:responseData[@"message"]
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                          handler:^(UIAlertAction * action) {
                                                                              
                                                                              [self loadData];
                                                                          }];
                    
                    [alert addAction:defaultAction];
                    [self presentViewController:alert animated:YES completion:nil];
                }];
            }

            
        }else{
            
            [self removeMenuView];
        }
    }
    
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        
        // 使用缓存行高，避免计算多次
        SquareModel * model = self.listArray[indexPath.row];
        return model.rowHeight;
    }else{
        
        return 40 * SCREENH6;
    }
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    if (tableView == self.tableView) {
        
        return 0;
    }else{
        
        if (section == 0) {
            
            return 20 * SCREENH6;
        }else{
            
            return 0;
        }
    }
    
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    if (tableView == self.tableView) {
        
        return nil;
    }else{
        
        if (section == 0) {
            
            GrayFooterView * header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"GrayFooterView"];
            
            return header;
        }else{
            
            return nil;
        }
    }
    
}

- (void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section{
    
    if ([view isKindOfClass:[UITableViewHeaderFooterView class]]) {
        ((UITableViewHeaderFooterView *)view).backgroundView.backgroundColor = ColorWithRGB(0xF0F0F0);
    }
}

- (void)clickItemButton:(UIButton *)type WithCell:(SquareTableViewCell *)cell{
    
    self.model = cell.model;
    [self didMenuButton];
}

- (void)clickLocalButtonLocal:(NSString *)local WithDynamic_latitude:(NSString *)latitude WithDynamic_longitude:(NSString *)longitude{
    
    HiddenBar;
    
    MapViewController * mapVC = [MapViewController new];
    
    mapVC.merchants_latitude = latitude;
    mapVC.merchants_longitude = longitude;
    mapVC.merchants_local = local;
    
    [self.navigationController pushViewController:mapVC animated:YES];
    
    ShowBar;
}

- (void)clickHeadImageViewWith:(NSString *)ID{
    
    HiddenBar;
    
    PersonalViewController * personVC = [PersonalViewController new];
    
    personVC.ID = ID;
    
    [self.navigationController pushViewController:personVC animated:YES];
    
    ShowBar;
}

- (void)clickGroupLabelWithCell:(SquareTableViewCell *)cell{
    
    NSDictionary * dict = @{@"id":cell.model.group_id};
    [[ZRNetworkTool sharedTool] checkGroupStatusWithDict:dict WithBlock:^(BOOL success, id responseData) {
        
//        NSLog(@"res===%@",responseData);
        if (success) {
            
            HiddenBar;
            GroupInfoViewController * infoVC = [GroupInfoViewController new];
            
            infoVC.group_id = cell.model.group_id;
            
            [self.navigationController pushViewController:infoVC animated:YES];
            
            ShowBar;
        }else{
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:responseData[@"message"]
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }];
    
}

- (void)clickAddButton{
    
    HiddenBar;
    
    PushNewsViewController * pushVC = [PushNewsViewController new];
    
    [self.navigationController pushViewController:pushVC animated:YES];
    
    ShowBar;
}

- (void)didMenuButton{
    
    [[ZRNetworkTool sharedTool] checkAttentionStatusWithAttention_user_id:self.model.user_id WithBlock:^(BOOL success, id responseData) {
        
        if (success) {
            
            NSDictionary * dict = responseData[@"data"];
            int is_attention = [dict[@"is_attention"] intValue];
            NSString * attention;
            if (is_attention == 1) {
                
                attention = @"取消关注";
            }else if (is_attention == 0){
                
                attention = @"关注";
            }
            
            
            self.titleArray = @[attention,@"私聊",@"邀请",@"屏蔽",@"举报"];
        }
        
    }];
    
    UIView * backView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    backView.backgroundColor = ZRBlackColor;
    backView.alpha = 0.4;
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeMenuView)];
    backView.userInteractionEnabled = YES;
    [backView addGestureRecognizer:tapGR];
    
    self.backView = backView;
    
    [self.tabBarController.view addSubview:self.backView];
    

    UITableView * menuView = [[UITableView alloc] initWithFrame:CGRectMake(0, kScreenH - kBarHeight - 260 * SCREENH6, kScreenW, 260 * SCREENH6)];
    
    menuView.delegate = self;
    menuView.dataSource = self;
    menuView.backgroundColor = ZRWhiteColor;
    menuView.separatorStyle = UITableViewCellSeparatorStyleNone;
    menuView.showsVerticalScrollIndicator = NO;
    
    self.menuView = menuView;
    
    [self.menuView registerClass:[MenuTableViewCell class] forCellReuseIdentifier:@"MenuTableViewCell"];
    [self.tableView registerClass:[GrayFooterView class] forHeaderFooterViewReuseIdentifier:@"GrayFooterView"];
    
    [self.tabBarController.view addSubview:self.menuView];
}

- (void)removeMenuView{
    
    [self.backView removeFromSuperview];
    [self.menuView removeFromSuperview];
}


@end
